package it.edgeworks.dsession.api;

import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author Ivan Diana
 * @version $Revision: 69 $
 */
public abstract class HttpSessionProviderBase implements HttpSessionProvider {

	protected final Log logger = LogFactory.getLog(getClass());

    /**
     * The default session timeout
     */
    protected static final int DEFAULT_TIMEOUT = 30 * 60; /* 30 min */

    protected int timeoutInSeconds;

    public void init(FilterConfig config) throws ServletException {
        timeoutInSeconds = DEFAULT_TIMEOUT;
        try {
            timeoutInSeconds = Integer.parseInt(config.getInitParameter("session-timeout"));
        } catch (Exception ignore) {
        }
    }

    @SuppressWarnings("unchecked")
    protected Map<String, Object> session2Map(HttpSession session) {
        Map<String, Object> toSerialize = new HashMap<String, Object>();
        Enumeration names = session.getAttributeNames();
        while (names.hasMoreElements()) {
            String attributeName = (String) names.nextElement();
            Object attributeValue = session.getAttribute(attributeName);
            logger.debug("MultiSessionFilter Attrib Session Map - " + attributeName + ":" + attributeValue);
            toSerialize.put(attributeName, attributeValue);
        }
        return toSerialize;
    }

    protected void map2session(Map serialized, HttpSession session){
    	//System.out.println(new Date() + " - map2session 1:" + serialized.size());
        for (Object obj : serialized.entrySet()) {
        	//System.out.println(new Date() + " - map2session 2");
            Map.Entry entry = (Map.Entry) obj;
        	//System.out.println(new Date() + " - map2session 3");
            session.setAttribute((String) entry.getKey(), entry.getValue());
        	//System.out.println(new Date() + " - map2session 4");
        }
    	//System.out.println(new Date() + " - map2session 5");
    }

    protected Date getExpireDatetime(int offsetSecond){
        GregorianCalendar calendar = (GregorianCalendar)GregorianCalendar.getInstance();        
        calendar.add(Calendar.SECOND, offsetSecond);
        return calendar.getTime();
    }
}
